package juc;

/**
 * @author 马迪迪
 * @description: TODO
 * @data 2025年10月10日23时17分
 */
public class MultiThreadNumberPrinter {

    private final int threadCount;
    private final int maxNumber;
    private volatile int currentTurn = 0;
    private volatile int currentNumber = 1;

    public MultiThreadNumberPrinter(int threadCount, int maxNumber) {
        this.threadCount = threadCount;
        this.maxNumber = maxNumber;
    }

    public void startPrinting() {
        Thread[] threads = new Thread[threadCount];

        // 创建并启动多个线程
        for (int i = 0; i < threadCount; i++) {
            final int threadId = i;
            threads[i] = new Thread(() -> printNumbers(threadId));
            threads[i].start();
        }

        // 等待所有线程执行完毕
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("Thread interrupted: " + e.getMessage());
            }
        }
    }

    private void printNumbers(int threadId) {
        while (true) {
            synchronized (this) {
                // 等待轮到当前线程执行
                while (currentTurn != threadId && currentNumber <= maxNumber) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }

                // 检查是否已经输出完所有数字
                if (currentNumber > maxNumber) {
                    notifyAll();
                    break;
                }

                // 输出当前数字
                System.out.println("Thread-" + threadId + ": " + currentNumber);
                currentNumber++;

                // 轮到下一个线程
                currentTurn = (currentTurn + 1) % threadCount;
                notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        // 示例：3个线程轮流输出1-10的数字
        MultiThreadNumberPrinter printer = new MultiThreadNumberPrinter(3, 10);
        printer.startPrinting();
    }

}
